package com.ma.gulimall.seckill.interceptor;

import com.ma.gulimall.constant.AuthServerConstant;
import com.ma.gulimall.vo.MemberResponseVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @ClassName LoginUserInterceptor
 * @Author: mayongqiang
 * @DATE 2021/11/1 21:38
 * @Description: 登录拦截器
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberResponseVo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // TODO: 2021/11/14   296P  放行别的请求  /order/order/status/{}
        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/kill", uri);
        if (match) {
            HttpSession session = request.getSession();
            MemberResponseVo attribute = (MemberResponseVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
            if (attribute != null) {
                //登录状态
                loginUser.set(attribute);
                return true;
            } else {
                //未登录，去登录
                request.getSession().setAttribute("msg", "请先登录！");
                response.sendRedirect("http://auth.gulimall.com/login.html");
                return false;
            }
        }
        return true;
    }
}
